package com.corecmd.tcloud.tcimserver.imclient.starter;

import com.corecmd.tcloud.tcimcommon.im.common.PacketDecoder;
import com.corecmd.tcloud.tcimcommon.im.common.PacketEncoder;
import com.corecmd.tcloud.tcimserver.imclient.handler.ClientHandler;
import com.corecmd.tcloud.tcimserver.imclient.handler.ClientLoginResponseHandler;
import com.corecmd.tcloud.tcimserver.imclient.handler.ClientMessageRequestHandler;
import com.corecmd.tcloud.tcimserver.imclient.handler.ClientMessageResponseHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @author : TianShaoJiao
 * @date : 2021/2/20
 * @description :
 **/
@Slf4j
public class ImClient {
    private String userId;
    private String userName;
    public ImClient(String userId,String userName){
        this.userId = userId;
        this.userName = userName;
    }
    public void start(String host,int port){
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap
                    // 1.指定线程模型
                    .group(workerGroup)
                    // 2.指定 IO 类型为 NIO
                    .channel(NioSocketChannel.class)
                    // 3.IO 处理逻辑
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) {
                            ch.pipeline().addLast(new PacketDecoder());
                            ch.pipeline().addLast(new ClientHandler(userId,userName));
                            ch.pipeline().addLast(new ClientLoginResponseHandler());
                            ch.pipeline().addLast(new ClientMessageRequestHandler());
                            ch.pipeline().addLast(new ClientMessageResponseHandler());
                            ch.pipeline().addLast(new PacketEncoder());
                        }
                    });
            // 4.建立连接
            ChannelFuture future = bootstrap.connect(host, port).sync();
            // 等待服务端监听端口关闭
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.info("客户端异常",e);
        }finally {
            workerGroup.shutdownGracefully();
        }
    }
}
